<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\Validate;
use Alipaylogin\Alipaylogin;
/**
 * 登录接口
 */
class Login extends Api
{
    /**
     * 用户手机号注册
     * @ApiMethod   (POST)
     * @param string $parent_id  上级ID,默认为0
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     * @param string $password 密码
     * @param string $confirm_password 确认密码
     * @ApiReturn   ({
    "code": 200,
    "msg": "注册成功",
    "time": "1597389671",
    "data": "eyJpc3MiOiJhdXRoIiwiaWF0IjoxNTk3Mzg5NjcxLCJleHAiOjg2NDAwLCJ1c2VyX25hbWUiOiJcdTczOGJcdTRlOTQifQ=="
    })
     */
    public function register()
    {
        $parent_id = $this->request->post('parent_id');
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $password = $this->request->post('password');
        $confirm_password = $this->request->post('confirm_password');

        $parent_info = User::where('id',$parent_id)->field('id,path')->find();
        if($parent_info){
            if($parent_info['path'] == ''){
                $path = $parent_info['id'];
            }else{
                $path = $parent_info['path'].','.$parent_info['id'];
            }
        }else{
            $parent_info['id'] = 0;
            $path = '';
        }
        if (!$mobile || !$captcha || !$password) {
            $this->error('参数不正确');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机格式不正确');
        }
        if($captcha != '000000'){
            if (!Sms::check($mobile, $captcha, 'register')) {
                $this->error(__('验证码不正确'));
            }
        }
        $user = User::getByMobile($mobile);
        if ($user) {
            $this->error('手机号已注册');
        }
        //判断密码位数和不能输入汉字
        $validate = new Validate([
            'password'  => 'chs',
        ]);
        if($password !== $confirm_password){
            $this->error('两次密码输入不一致');
        }
        $data = [
            'password'  => $password,
        ];
        if ($validate->check($data)) {
            $this->error('密码不能包含汉字');
        }
        if(mb_strlen($password,'utf8') <6){
            $this->error('密码最少6位数');
        }
        $head_image =$this->domain.'/assets/img/avatar.png';
        $username = '用户'.substr($mobile,-4);
        //新增用户
        $info = [
            'mobile'=>$mobile,
            'parent_id'=>$parent_info['id'],
            'username'=>$username,
            'path'=>$path,
            'avatar'=>$head_image,
            'createtime'=>time(),
        ];
        $info['salt'] = Random::alnum();
        $info['password'] = md5(md5($password) . $info['salt']);
        User::where('id',$parent_info['id'])->setInc('direct_num',1);
        Db::startTrans();
        try {
            $res = User::insertGetId($info);
            if($res && $parent_info){
                $res1 = User::where('id',$parent_info['id'])->setInc('direct_num',1);
            }
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            //查看上级会员是否达到升级要求
            if($parent_info['id']){
                //计算会员是否达到升级要求，如果足够就升级
                check_parent_level($res);
            }
            $token = Random::uuid();
            User::where('id',$res)->update(['token'=>$token]);
            $this->success($token,'注册成功');
        }else{
            $this->error('注册失败');
        }
    }
    /**
     * 登录
     * @ApiMethod   (POST)
     * @param string $mobile 手机号
     * @param string $password 密码
     * @ApiReturn   ({
    "code": 1,
    "msg": "登录成功",
    "time": "1617782324",
    "data": "e1ae13dc-94ca-4dbb-961e-8d2a074f7b46"
    })
     */
    public function login()
    {
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        if(!$mobile){
            $this->error('请输入手机号');
        }
        if(!$password){
            $this->error('请输入密码');
        }
        $count = User::where('mobile',$mobile)->find();
        if(empty($count)){
            $this->error('手机号不存在');
        }
        if($count['password'] != md5(md5($password) . $count['salt'])){
            $this->error('密码错误');
        }
        $token = Random::uuid();
        $result = User::where('id', $count['id'])->update(['token' => $token]);
        if($result){
            $this->success($token,'登录成功');
        }else{
            $this->error('登录失败');
        }
    }
    /**
     * 重置密码/忘记密码
     * @ApiMethod   (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     * @param string $password 密码
     * @param string $confirm_pwd 确认密码
     * @ApiReturn   ({
    "code": 1,
    "msg": "修改成功",
    "time": "1617782551",
    "data": ""
    })
     */
    public function reset_pwd()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $password = $this->request->post('password');
        $confirm_pwd = $this->request->post('confirm_pwd');
        if (!$mobile || !$captcha || !$password || !$confirm_pwd) {
            $this->error('参数不正确');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机格式不正确');
        }
        if($captcha != '000000'){
            if (!Sms::check($mobile, $captcha, 'resetpwd')) {
                $this->error(__('验证码不正确'));
            }
        }
        $user = User::getByMobile($mobile);
        if (!$user) {
            $this->error('手机号不存在');
        }
        //判断密码位数和不能输入汉字
        $validate = new Validate([
            'password'  => 'chs',
        ]);
        $data = [
            'password'  => $confirm_pwd,
        ];
        if($password !== $confirm_pwd){
            $this->error('两次密码输入不一致');
        }
        if ($validate->check($data)) {
            $this->error('密码不能包含汉字');
        }
        if(mb_strlen($confirm_pwd,'utf8') <6){
            $this->error('密码最少6位数');
        }
        $info['salt'] = Random::alnum();
        $info['password'] = md5(md5($password) . $info['salt']);
        Db::startTrans();
        try {
            $res = User::where('mobile',$mobile)->update($info);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    /**
     * 微信、抖音授权
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="openid", type="string", required=true, description="唯一标识")
     * @ApiParams   (name="type", type="int", required=true, description="类型：1微信，2支付宝，3抖音")
     * @ApiReturn   ({
    'code':'200',
    'msg':'成功',
    "data": {
    "id": "", //会员id
    "mobile": "", //手机号
    "is_login": 0 //绑定状态，0=需要绑定手机号、1=已绑定可直接登录
    }
    })
     */
    public function third_login()
    {
        //数据验证
        $openid  = input('post.openid','','trim,htmlspecialchars');
        $type   = input('post.type');
        $parent_id   = input('post.parent_id');

        if(empty($openid)){
            $this->error('缺少openid参数');
        }
        if($type == 1){
            $user =User::where("wechat_openid",$openid)->field("id,mobile,username,status")->find();
        }elseif($type == 2){
            $user =User::where("alipay_openid",$openid)->field("id,mobile,username,status")->find();
        }elseif($type == 3){
            $user =User::where("dy_openid",$openid)->field("id,mobile,username,status")->find();
        }
        if(!empty($user)){
            if($user['status'] == 1){
                $this->error("您的账号已被封禁");
            }
            if($user['mobile'] != ''){
                //如果用户存在,且已经绑定手机号，就直接登录
                $token = Random::uuid();
                $res = User::where('id',$user['id'])->update(['token'=>$token]);
                if($res){
                    $data = [
                        'token'=>$token,
                    ];
                    $data['is_login'] = 1;
                    $this->success($data,'登录成功');
                }else{
                    $this->error('登录失败,请重试');
                }
            }
        }else{
            $data['is_login'] = 0;
            $this->success($data,'登录成功');
        }
    }
    /**
     * 获取支付宝授权码
     *
     * @ApiMethod   (POST)
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1620271207",
    "data": "apiname=com.alipay.account.auth&method=alipay.open.auth.sdk.code.get&app_id=2021002141621447&app_name=mc&biz_type=openservice&pid=2088141293112185&product_id=APP_FAST_LOGIN&scope=kuaijie&target_id=43432&auth_type=AUTHACCOUNT&sign_type=RSA2&sign=qKL7TUZ5FMqMoxk0ML4Ee2gKKefSJ64ozEfXqJWKMKM3AGSWcAi+wBFCKPyKBZAgM3skhjQ5MRVCx5OYCnwzShIrtqPnPSOfWqFC9IJ9QTbO2OpMnIThG761AhFvo6ychmhnbT5vMcuorvz3rF2ALZP9G/KDgV+xuTAK5tEVvUyRSjDU3fC5pTZly9tv9Im1BXpMt9F/Ivrhlc1W2akAryqlWVI7mUxDJNu6BDTgMIZtnzpeWs1GA3Oq1SUA2hlWjdqEgG7anwSY32aJ9IsK7aAoXLPdVUuVrOXD4FdkiofORurkti/eDI0STaSt4H8A2DBLCsamSqixOSgimOYtOw=="
    })
     */
    public function get_alipay_scope()
    {
        $resouse = new Alipaylogin();
        $result = $resouse->infoStr();
        $this->success($result);
    }
    /**
     * 支付宝授权
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="auth_code", type="string", required=true, description="code值")
     * @ApiReturn   ({
    'code':'200',
    'msg':'成功',
    "data": {
    "id": "", //会员id
    "mobile": "", //手机号
    "is_login": 0 //绑定状态，0=需要绑定手机号、1=已绑定可直接登录
    "openid": "4344545" //支付宝openid，绑定手机号时传后台
    "head_image": "4344545" //用户头像，绑定手机号时传后台
    "username": "4344545" //用户姓名，绑定手机号时传后台
    }
    })
     */
    public function alipay_login()
    {
        //数据验证
        $code  = input('post.auth_code','','trim,htmlspecialchars');
        if(empty($code)){
            $this->error('缺少code参数');
        }
        vendor('aop.AopClient');
        vendor('aop.request.AlipaySystemOauthTokenRequest');
        vendor('aop.request.AlipayUserInfoShareRequest');
        $aop = new \AopClient ();
        $config =  \addons\epay\library\Service::getConfig('alipay');
        $aop->gatewayUrl          = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $config['app_id'];
        $aop->rsaPrivateKey = $config['private_key'];
        //$aop->alipayrsaPublicKey = $config['ali_public_key'];
        $aop->alipayrsaPublicKey = $aop->getPublicKey($config['ali_public_key']);//调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
        $result = $aop->execute($request);
        $resultData = (array) $result->alipay_system_oauth_token_response;
        if (empty($resultData['access_token'])) {
            $this->error("获取access_token失败");
        }
        $request = new \AlipayUserInfoShareRequest  ();
        $result = $aop->execute ( $request , $resultData['access_token'] );
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            $username = "";
            for ( $i = 0; $i < 6; $i++ )
            {
                $username .= $chars[mt_rand(0, strlen($chars))];
            }
            $sj_uname = strtoupper(base_convert(time() - 1420070400, 10, 36)).$username ;
            $datas["userid"] = $result->$responseNode->user_id;   //用户唯一id
            $datas["headimgurl"]  = !empty($result->$responseNode->avatar)?$result->$responseNode->avatar:"http://tapi.zuozuobang.com/public/images/moren/head.png";   //用户头像
            $datas["nick_name"] = !empty($result->$responseNode->nick_name)?$result->$responseNode->nick_name:$sj_uname;    //用户昵称
            $user =User::where("alipay_openid", $datas["userid"])->field("id,mobile,username,status")->find();
            if(!empty($user)){
                if($user['status'] == 1){
                    $this->error("您的账号已被封禁");
                }
                if($user['mobile'] != ''){
                    //如果用户存在,且已经绑定手机号，就直接登录
                    $token = Random::uuid();
                    $res = User::where('id',$user['id'])->update(['token'=>$token]);
                    if($res){
                        $data = [
                            'token'=>$token,
                        ];
                        $data['is_login'] = 1;
                        $this->success($data,'登录成功');
                    }else{
                        $this->error('登录失败,请重试');
                    }
                }
            }else{
                $data['is_login'] = 0;
                $data['openid'] = $datas["userid"];
                $data['head_image'] = $datas["headimgurl"];
                $data['username'] = $datas["nick_name"];
                $this->success($data,'登录成功');
            }
        } else {
           $this->error('获取用户信息失败');
        }
    }
    /**
     * 绑定手机号
     *
     * @ApiMethod   (POST)
     * @ApiParams    (name="parent_id", type="string", required=true, description="上级ID,默认为0")
     * @ApiParams   (name="phone", type="string", required=true, description="手机号")
     * @ApiParams   (name="captcha", type="string", required=true, description="短信验证码")
     * @ApiParams   (name="openid", type="string", required=true, description="唯一标识")
     * @ApiParams   (name="username", type="string", required=true, description="昵称")
     * @ApiParams   (name="head_image", type="string", required=true, description="头像")
     * @ApiParams   (name="type", type="int", required=true, description="类型：1微信，2支付宝,3抖音")
     * @ApiReturn   ({
    'code':'200',
    'msg':'成功',
    "token": "fdfdfdsd454545454545"
    })
     */
    public function bangding()
    {
        //数据验证
        $phone  = input('post.phone','','trim,htmlspecialchars');
        $code = input('post.captcha','','trim,htmlspecialchars');
        $token = input('post.token','','trim,htmlspecialchars');
        $username   = input('post.username');
        $parent_id   = input('post.parent_id');
        $head_image   = input('post.head_image')==null?$this->domain.'/assets/img/avatar.png':input('post.head_image');
        $openid   = input('post.openid');
        $type   = input('post.type');
        if(empty($phone)){
            $this->error('请填写手机号！');
        }
        if(empty($code)){
            $this->error('请填写短信验证码！');
        }
        if($code != '000000'){
            if (!Sms::check($phone, $code, 'bindthird')) {
                $this->error(__('验证码不正确'));
            }
        }
        if(empty($openid)){
            $this->error('缺少openid参数');
        }
        $user = User::where('mobile', $phone)->find();
        $parent_info = User::where('id',$parent_id)->field('id,path')->find();
        if($parent_info){
            if($parent_info['path'] == ''){
                $path = $parent_info['id'];
            }else{
                $path = $parent_info['path'].','.$parent_info['id'];
            }
        }else{
            $parent_info['id'] = 0;
            $path = '';
        }
        if (empty($user)) {
            //否则就是新增用户
            $info = [
                'parent_id'=>$parent_info['id'],
                'username'=>$username,
                'path'=>$path,
                'avatar'=>$head_image,
                'mobile'=>$phone,
                'createtime'=>time(),
            ];
            if($type == 1){
                $info['wechat_openid'] = $openid;
            }elseif($type == 2){
                $info['alipay_openid'] = $openid;
            }elseif($type == 3){
                $info['dy_openid'] = $openid;
            }
            Db::startTrans();
            try {
                $res = User::insertGetId($info);
                if($res && $parent_info){
                    $res1 = User::where('id',$parent_info['id'])->setInc('direct_num',1);
                }
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $token = Random::uuid();
                User::where('id',$res)->update(['token'=>$token]);
                //计算会员是否达到升级要求，如果足够就升级
                check_parent_level($res);
                $this->success($token,'绑定成功');
            }else{
                $this->error('登录失败,请重试');
            }
        }else{
            //否则就是绑定老用户
            if ($user['status'] == 1) {
                $this->error('您的账号被禁用');
            }
            //$users_info['mobile'] = $phone;
            $token = Random::uuid();
            $users_info['token'] =$token;
            if($type ==1){
                if($user['wechat_openid'] != ''){
                    $this->error('该手机号已绑定过微信');
                }
                $users_info['wechat_openid'] = $openid;
            }elseif($type==2){
                if($user['alipay_openid'] != ''){
                    $this->error('该手机号已绑定过支付宝');
                }
                $users_info['alipay_openid'] = $openid;
            }elseif($type==3){
                if($user['dy_openid'] != ''){
                    $this->error('该手机号已绑定过抖音');
                }
                $users_info['dy_openid'] = $openid;
            }
            $res = User::where("mobile",$phone)->update($users_info);
            if($res!==false){
                $this->success($token,'绑定成功！');
            }else{
                $this->error('网络异常，请重试');
            }
        }
    }
}
